//
//  DeviceFingerPrintingVC.m
//  CityDOSDK
//
//  Created by CityDo on 2018/10/27.
//  Copyright © 2018年 Liu Lingbo. All rights reserved.
//

#import "DeviceFingerPrintingVC.h"
#import "UIDevice+Device.h"
#import "UIDevice+CityDOFCUUID.h"
#import "CitydoCheckDeviceInfoManager.h"
#import "CitydoCheckNetWorkInfoManager.h"
#import "CitydoCheckAFAppDotNetAPIClient.h"
//CitydoCheckAFAppDotNetAPIClient
//CitydoChecklocationGPS
#import <MapKit/MapKit.h>
#import "CitydoChecklocationGPS.h"
#import "CitydoCheckLocationManager.h"
#import "CitydoCheckUrlManage.h"
#import "CityDOCatchCrash.h"
#import "Constants.h"

@interface DeviceFingerPrintingVC ()<MKMapViewDelegate>{
    CitydoChecklocationGPS *loc;
    CitydoCheckLocationManager *locManager;
}

@property (copy, nonatomic) NSString *longitude;//经度
@property (copy, nonatomic) NSString *latitude;//纬度
@property (copy, nonatomic) NSString *address; //地址
@property (strong,nonatomic) NSDictionary *dictLocation;

/////////////////设备指纹属性
@property (strong, nonatomic) NSString * RAM;  //内存(上市信息)
@property (strong, nonatomic) NSString * accessApp ;//访问设备指纹服务的应用
@property (strong, nonatomic) NSString * accessTime;//访问设备指纹服务的时间
@property (strong, nonatomic) NSString * appType;//设备类型(android,iOS,pc),实际上是操作系统类型
@property (strong, nonatomic) NSString * brand;//手机品牌(上市信息)
@property (strong, nonatomic) NSString * city;//城市*******
@property (strong, nonatomic) NSString * country;//国家******
@property (strong, nonatomic) NSString * cpu;//CPU信息(上市信息)
@property (strong, nonatomic) NSString * cpuName;//CPU名称
@property (strong, nonatomic) NSString * cpuNumber;//CPU核心数
@property (strong, nonatomic) NSString * cpuType;//CPU类型
@property (strong, nonatomic) NSString * cpuFrequency;//CPU频率
@property (strong, nonatomic) NSString * busFrequency;//总线频率
@property (copy, nonatomic)   const NSString * deviceType;//设备类型（PC,MOBILE）
@property (strong, nonatomic) NSString * diskSpace;//硬盘(上市信息)
@property (strong, nonatomic) NSString * ip;//设备ip
@property (strong, nonatomic) NSString * isEmulator;//是否模拟器
@property (strong, nonatomic) NSString * isJailbreak;//是否越狱
@property (strong, nonatomic) NSString * isProxy;//是否代理
@property (strong, nonatomic) NSString * isRoot;//是否root//android特有的属性
@property (strong, nonatomic) NSString * isVM;//是否虚拟机
@property (strong, nonatomic) NSString * isVpn;//是否vpn
@property (strong, nonatomic) NSString * location;//地理定位的经纬度********
@property (strong, nonatomic) NSString * networkType;//网络类型（2G,3G,4G,WIFI,UNKNOWN）
@property (strong, nonatomic) NSString * operatorSystem;//系统(上市信息)
@property (strong, nonatomic) NSString * os;//操作系统
@property (strong, nonatomic) NSString * osVersion;//操作系统版本号
@property (strong, nonatomic) const NSString * platform;//手机型号(上市信息)
//@property (strong, nonatomic) NSString * price;//上市价格(上市信息)
@property (strong, nonatomic) NSString * region;//省份********
@property (strong, nonatomic) NSString * resolution;//设备分辨率
@property (strong, nonatomic) NSString * screenDPI;//屏幕尺寸(上市信息)
@property (strong, nonatomic) NSString * screenSize;//屏幕分辨率(上市信息)
@property (strong, nonatomic) NSString * shellSize;//尺寸(上市信息)
@property (strong, nonatomic) NSString * shellColor;//外壳颜色(上市信息) iOS 上线会被拒，私有API
/*手机应用列表    Android 可以获取,部分应用市场可能会限制获取.  iOS9-10可获取.*/
@property (strong, nonatomic) NSString * appList;//手机应用列表
@property (strong, nonatomic) NSString * CarrierInfo;//运营商名称
@property (strong, nonatomic) NSString * currentIP;//当前iP
@property (strong, nonatomic) NSString * wifiSsid;//当前ssid
@property (strong, nonatomic) NSString * wifiBssid;//当前Bssid 也是mac地址
@property (strong, nonatomic) NSString * wifiName;//当前名称
@property (strong, nonatomic) NSString * wifiSignalStrength;//当前WIFI强度

@property (strong, nonatomic) NSString * wifiInfo;//wifi信息

@property (strong, nonatomic) NSString * timeToMarket;//上市时间(上市信息)    后台生成
@property (strong, nonatomic) NSString * score;//设备环境安全系数    后台生成安全系数.
@property (strong, nonatomic) NSString * deviceId;//设备指纹    后台生成唯一标识.
@property (strong, nonatomic) NSString * picture;//图片(上市信息)    后台获取第三方信息.
@property (strong, nonatomic) NSString * status;//本次请求到应答状态码

//设备运动管理类对象
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (strong, nonatomic) NSString *accelerationText;//加速度计
@property (strong, nonatomic) NSString *gravityLabText;//重力计
@property (strong, nonatomic) NSString *gyroDataText;//陀螺仪
@property (strong, nonatomic) NSString *magnetometerLabText;//磁力针

@property (copy,nonatomic)    NSDictionary *dict;
@property (copy,nonatomic)    NSDictionary *cpuDict;
@property (copy,nonatomic)    NSDictionary *wifiDict;

@end

@implementation DeviceFingerPrintingVC

- (NSMutableDictionary *)mutableDict
{
    if (!_mutableDict) {
        _mutableDict = [NSMutableDictionary dictionary];
    }
    return _mutableDict;
}

+ (DeviceFingerPrintingVC *)sharedInstance;
{
    static DeviceFingerPrintingVC*_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[DeviceFingerPrintingVC alloc] init];
        CityDOCatchCrash *crashInfo = [[CityDOCatchCrash alloc]init];
        [crashInfo redirectNSLogToDocumentFolder];
    });
    
    return _sharedInstance;
}

//- (void)viewDidLoad {
//    [super viewDidLoad];
//}

-(void)TestAddressInfo:(NSDictionary *)dict;
{
    [self postExceptionMessage];
    loc= [CitydoChecklocationGPS sharedlocationGPS];
    [loc getAuthorization];//授权
    [loc startLocation];//开始定位
    __block DeviceFingerPrintingVC * weakSelf = self;
    
    loc.locationCompleteBlock = ^(double longitude, double latitude) {
        double a = longitude;
        double b = latitude;
        weakSelf.longitude = [NSString stringWithFormat:@"%.14f",longitude];
        weakSelf.latitude = [NSString stringWithFormat:@"%.14f",latitude];
        
        NSDictionary *params = @{@"longitude":weakSelf.longitude,@"latitude":weakSelf.latitude};
        
        weakSelf->_location = [CitydoCheckAFAppDotNetAPIClient dataTOjsonString:params];
        [weakSelf->_mutableDict setValue:weakSelf->_location forKey:@"location"];
        
        //反地理编码
        weakSelf->locManager = [[CitydoCheckLocationManager alloc] init];
        [weakSelf->locManager reverseGeocodeWithlatitude:latitude longitude:longitude success:^(id dictt) {
            weakSelf->_dictLocation = dictt;
            [weakSelf->_mutableDict addEntriesFromDictionary:dictt];
            [weakSelf postDeviceFingerPrinting:weakSelf->_mutableDict];
        } failure:^{
            
        }];
    };
}

-(void)TestDeviceInfo:(NSDictionary *)dict;

{
    [self postExceptionMessage];
    [self.mutableDict addEntriesFromDictionary:dict];
    
    
    _deviceId = [[UIDevice currentDevice] uuid];
    [_mutableDict setValue:_deviceId forKey:@"deviceId"];

    _RAM = [NSString stringWithFormat:@"%f", [UIDevice getMemoryMB]];
    if (_RAM == nil) {
        _RAM = @"";
    }
    [_mutableDict setValue:_RAM forKey:@"ram"];
    
    _accessApp = [UIDevice getAppName];
    
    if (_accessApp == nil) {
        _accessApp = @"";
    }
    
    [_mutableDict setValue:_accessApp forKey:@"accessApp"];
    
    _accessTime = [UIDevice getCurrentTimes];
    if (_accessTime == nil) {
        _accessTime = @"";
    }
    [_mutableDict setValue:_accessTime forKey:@"accessTime"];
    
    _appType  =  [[UIDevice currentDevice] systemName];
    if (_appType == nil) {
        _appType = @"";
    }
    
    [_mutableDict setValue:_appType forKey:@"appType"];
    [_mutableDict setValue:@"苹果" forKey:@"brand"];
    
    _cpuName = [[CitydoCheckDeviceInfoManager sharedManager] getCPUProcessor];
    if (_cpuName == nil) {
        _cpuName = @"";
    }
    _cpuNumber = [NSString stringWithFormat:@"%ld",(long)[UIDevice getCPUNum]];
    if (_cpuNumber == nil) {
        _cpuNumber = @"";
    }
    
    _cpuType = [UIDevice getCPUType];
    if (_cpuType == nil) {
        _cpuType = @"";
    }
    _cpuFrequency = [NSString stringWithFormat:@"%lu",(unsigned long)[UIDevice getCpuFrequency]];
    if (_cpuFrequency == nil) {
        _cpuFrequency = @"";
    }
    
    _busFrequency =[NSString stringWithFormat:@"%lu",(unsigned long)[UIDevice getBusFrequency]];
    if (_busFrequency == nil) {
        _busFrequency = @"";
    }
    
    _cpuDict = @{@"cpuName":_cpuName,@"cpuNumber":_cpuNumber,@"cpuType":_cpuType,@"cpuFrequency":_cpuFrequency,@"busFrequency":_busFrequency};
    
    _cpu = [CitydoCheckAFAppDotNetAPIClient dataTOjsonString:_cpuDict];
    [_mutableDict setValue:_cpu forKey:@"cpu"];
    
    _deviceType = [[CitydoCheckDeviceInfoManager sharedManager] getDeviceName];
    if (_deviceType == nil) {
        _deviceType = @"";
    }
    [_mutableDict setValue:_deviceType forKey:@"deviceType"];
    
    int64_t totalDisk = [[CitydoCheckDeviceInfoManager sharedManager] getTotalDiskSpace];
    _diskSpace = [NSString stringWithFormat:@"%.2f GB", totalDisk/1024/1024/1024.0];
    //    _diskSpace = [NSString stringWithFormat:@"%.2lld ", totalDisk];
    
    if (_diskSpace == nil) {
        _diskSpace = @"";
    }
    
    [_mutableDict setValue:_diskSpace forKey:@"diskSpace"];
    
    _ip = [[CitydoCheckNetWorkInfoManager sharedManager] getIPAddress:NO];
    if (_ip == nil) {
        _ip = @"";
    }
    [_mutableDict setValue:_ip forKey:@"ip"];
    
    _isEmulator = [NSString stringWithFormat:@"%d", [UIDevice isSimulator]];
    if (_isEmulator == nil) {
        _isEmulator = @"";
    }
    [_mutableDict setValue:_isEmulator forKey:@"isEmulator"];
    
    _isJailbreak = [NSString stringWithFormat:@"%d", [UIDevice isJailbreak]];
    if (_isJailbreak == nil) {
        _isJailbreak = @"";
    }
    [_mutableDict setValue:_isJailbreak forKey:@"isJailbreak"];
    
    _isProxy = [NSString stringWithFormat:@"%d", [UIDevice isProxy]];
    if (_isProxy == nil) {
        _isProxy = @"";
    }
    [_mutableDict setValue:_isProxy forKey:@"isProxy"];
    
    _isRoot = [NSString stringWithFormat:@"%d", [UIDevice isProxy]];
    if (_isRoot == nil) {
        _isRoot = @"";
    }
    [_mutableDict setValue:_isRoot forKey:@"isRoot"];
    
    if (_isVM == nil) {
        _isVM = @"";
    }
    
    _isVM = [NSString stringWithFormat:@"%d", [UIDevice isSimulator]];
    [_mutableDict setValue:_isVM forKey:@"isVM"];
    
    if (_isVpn == nil) {
        _isVpn = @"";
    }
    
    _isVpn = [NSString stringWithFormat:@"%d", [UIDevice isVPNConnected]];
    [_mutableDict setValue:_isVpn forKey:@"isVpn"];
    
    _networkType = [UIDevice getNetWorkInfo];
    if (_networkType == nil) {
        _networkType = @"";
    }
    [_mutableDict setValue:_networkType forKey:@"networkType"];
    
    _operatorSystem = [[UIDevice currentDevice] systemName];
    _os = [[UIDevice currentDevice] systemName];
    if (_operatorSystem == nil) {
        _operatorSystem = @"";
    }
    if (_os == nil) {
        _os = @"";
    }
    [_mutableDict setValue:_operatorSystem forKey:@"operatorSystem"];
    [_mutableDict setValue:_os forKey:@"os"];
    
    _osVersion = [[UIDevice currentDevice] systemVersion];
    if (_osVersion == nil) {
        _osVersion = @"";
    }
    [_mutableDict setValue:_osVersion forKey:@"osVersion"];
    //不全
    //     _platform = [NSString stringWithFormat:@"%lu", (unsigned long)[UIDevice getDeviceType]];
    _platform = [[CitydoCheckDeviceInfoManager sharedManager] getDeviceName];
    if (_platform == nil) {
        _platform = @"";
    }
    [_mutableDict setValue:_platform forKey:@"platform"];
    
    _resolution = [UIDevice getScreenSize];
    _screenDPI = [UIDevice getScreenSize];
    _screenSize = [UIDevice getScreenSize];
    _shellSize = [UIDevice getScreenSize];
    if (_resolution == nil) {
        _resolution = @"";
        _screenDPI = @"";
        _screenSize = @"";
        _shellSize = @"";
    }
    
    [_mutableDict setValue:_resolution forKey:@"resolution"];
    [_mutableDict setValue:_screenDPI forKey:@"screenDPI"];
    [_mutableDict setValue:_screenSize forKey:@"screenSize"];
    [_mutableDict setValue:_shellSize forKey:@"shellSize"];
    
    _CarrierInfo = _CarrierInfo?[UIDevice getCarrierInfo]:@"";//中国电信
    if (_CarrierInfo == nil) {
        _CarrierInfo = @"";
    }
    _currentIP = [UIDevice getIPAddress:NO];//172.16.20.38
    if (_currentIP == nil) {
        _currentIP = @"";
    }
    _wifiSsid = [[CitydoCheckNetWorkInfoManager sharedManager] getWifiSSID];//Powecn-All
    if (_wifiSsid == nil) {
        _wifiSsid = @"";
    }
    _wifiName = [self wifiName];//Powecn-All
    if (_wifiName == nil) {
        _wifiName = @"";
    }
    _wifiSignalStrength = [[CitydoCheckNetWorkInfoManager sharedManager] getSignalStrength];
    
    //    NSString *wifiSsid2 = [UIDevice wifiSsid];//Powecn-All
    
    _wifiBssid = [[CitydoCheckNetWorkInfoManager sharedManager] getWifiBSSID];//58:6a:b1:29:ce:a0
    
    if (_wifiBssid == nil) {
        _wifiBssid = @"";
    }
    
    if (_wifiSignalStrength == nil) {
        _wifiSignalStrength = @"";
    }
    
    _motionManager = [[CMMotionManager alloc] init];
    NSDictionary *transducerDic = @{@"gravityLabText":@(_motionManager.gyroAvailable) ,@"accelerationText":@(_motionManager.accelerometerAvailable),@"gyroDataText": @(_motionManager.gyroAvailable),@"magnetometerLabText":@(_motionManager.magnetometerAvailable)};
    
    _wifiDict = @{@"CarrierInfo":_CarrierInfo,@"currentIP":_currentIP,@"wifiSsid":_wifiSsid,@"wifiBssid":_wifiBssid,@"wifiName":_wifiName,@"wifiSignalStrength":_wifiSignalStrength};
    _wifiInfo = [CitydoCheckAFAppDotNetAPIClient dataTOjsonString:_wifiDict];
    [_mutableDict setValue:_wifiInfo forKey:@"wifiInfo"];
    [_mutableDict addEntriesFromDictionary:transducerDic];
//#warn 以下两行代码用于测试崩溃
//    [self performSelector:@selector(test:)];
//    //
//    [[NSMutableDictionary dictionaryWithCapacity:0] setValue:nil forKey:@"key"];

}

-(void)getAllDeviceInfo:(NSDictionary *)dict;
{
    @try {
        [self TestDeviceInfo:dict];
    } @catch (NSException *exception) {
        NSLog(@"设备指纹数据获取失败==error  : %@", exception.reason);
        _status = exception.reason;
        
        if (_status == nil) {
            _status = @"";
        }
        [_mutableDict setValue:_status forKey:@"status"];
        [self postDeviceFingerPrinting:_mutableDict];
    } @finally {
        // 即使出现异常，仍旧去处理的事务
    }
}

-(void)getAddressInfo:(NSDictionary *)dict;
{
    @try {
        [self TestAddressInfo:dict];
    } @catch (NSException *exception) {
        NSLog(@"设备指纹尊重的地理信息数据获取失败==error  : %@", exception.reason);
        _status = exception.reason;
        
        if (_status == nil) {
            _status = @"";
        }
        [_mutableDict setValue:_status forKey:@"status"];
        [self postDeviceFingerPrinting:_mutableDict];
    } @finally {
        // 即使出现异常，仍旧去处理的事务
    }
}

-(void)postExceptionMessage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logDirectory = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Log"];
    NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    
    NSDictionary *infoDictionary=[[NSBundle mainBundle] infoDictionary];
    //     当前应用名称
    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSLog(@"当前应用名称：%@",appCurName);
    
    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSLog(@"当前应用版本号码：%@",appCurVersionNum);
    //NSString类方法读取内容
    NSString *breakLog = [NSString stringWithContentsOfFile:logFilePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"NSString类方法读取的内容是：\n%@",breakLog);
    
    NSDictionary *dict=@{@"name":appCurName,@"version":appCurVersionNum,@"breakLog":breakLog,@"dateStr":dateStr};
    
    //    @"http://172.16.16.77:8180/safe/other/insertBreakLog";
    
    NSString *tempURL1 = [CitydoCheckUrlManage sharedManager].otherInsertBreakLog;
    
    NSString *tempURL =@"http://172.16.16.77:8180/safe/other/insertBreakLog";
    
    
    [CitydoCheckAFAppDotNetAPIClient postAsynchronous:tempURL parameter:dict successBlock:^(NSDictionary *result, NSError *error) {
        NSInteger i = [[result objectForKey:@"code"] integerValue];
        if ( i==0 ) {
            DLog(@"===============崩溃信息上传存成功===============");
            [self deleteFile];
        } else {
            NSLog(@"===============崩溃信息上传存失败===============");
            NSLog(@"设备指纹数据保存失败=error  : %@", error.description);
        }
    } errorBlock:^(NSError *error) {
        NSLog(@"===============网络错误===============");
    }];

}

- (void)postDeviceFingerPrinting:(NSDictionary *)dict;
{
    
//    NSString *tempURL = [CitydoCheckUrlManage sharedManager].deviceFingerPrinting;
    
    if (!self.deviceFingerPrintingURL) {
        self.deviceFingerPrintingURL = @"";
        NSLog(@" ===============设备指纹数据请求的URL为空===============");
    }
    
    [CitydoCheckAFAppDotNetAPIClient postAsynchronous:self.deviceFingerPrintingURL parameter:_mutableDict successBlock:^(NSDictionary *result, NSError *error) {
        NSInteger i = [[result objectForKey:@"code"] integerValue];
        if ( i==0 ) {
            NSLog(@"===============设备指纹数据保存成功===============");
        } else {
            NSLog(@"===============设备指纹数据保存失败===============");
            NSLog(@"设备指纹数据保存失败=error  : %@", error.description);
        }
    } errorBlock:^(NSError *error) {
        NSLog(@"===============网络错误===============");
    }];
}

- (NSString *)wifiName;
{
    NSString *ssid = @"无Wi-Fi";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            ssid = [dict valueForKey:@"SSID"];
        }
    }
    
    if (!ssid) {
        return @"";
    }
    NSLog(@"======%@++++++",ssid);
    return ssid;
}

- (void)deleteFile {
    NSString *logDirectory =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
    BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
    if (isSuccess) {
        NSLog(@"delete success");
    }else{
        NSLog(@"delete fail");
    }
}

-(NSString *)getDocumentsPath {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logDirectory = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Log"];
    
    return logDirectory;
}

+ (NSDictionary *)dicGetAllDeviceInfo :(NSDictionary *)dict;
{
    NSString *udid  = [[UIDevice currentDevice] uuid];
    
    dict =  @{@"userId":udid};
    
    //    [_deviceFingerPrintingVC postExceptionMessage];
//    [self getAllDeviceInfo:dict];
//    [DeviceFingerPrintingVC getAddressInfo:dict];
    [[self sharedInstance]getAllDeviceInfo:dict];
    [[self sharedInstance] getAddressInfo:dict];
    return [self sharedInstance].mutableDict;
}


@end
